/**
 * 功能说明：Axios 实例创建与配置，统一拦截器、错误处理与通用方法封装。
 */
import axios from 'axios'
import store from '../store'
import { CONFIG } from '../config'

// 保存默认适配器以便在关闭 mock 时回退到原生 XHR
const defaultAdapter = axios.defaults.adapter

// 创建实例并设置基础 URL
const http = axios.create({
  baseURL: CONFIG.BASE_URL,
  timeout: 10000
})

// 请求拦截器：注入认证 token
http.interceptors.request.use(
  (config) => {
    const token = store.state.auth.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}` // 行内注释：标准 Bearer token 格式
    }
    return config
  },
  (error) => {
    store.dispatch('error/handleError', error)
    return Promise.reject(error)
  }
)

// 响应拦截器：统一成功与错误处理
http.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    const { response } = error
    const normalized = {
      message: response?.data?.message || error.message,
      status: response?.status || 0
    }
    store.dispatch('error/handleError', normalized)
    return Promise.reject(normalized)
  }
)

// MOCK 适配器：基于 axios adapter 提供离线示例能力
if (CONFIG.USE_MOCK) {
  http.defaults.adapter = async function mockAdapter(config) {
    const url = config.url || ''
    const method = (config.method || 'get').toLowerCase()
    // 模拟网络延迟
    const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
    await sleep(200)

    // 登录接口
    if (url.startsWith('/auth/login') && method === 'post') {
      const { username, password } = config.data || {}
      if (username && password) {
        return {
          data: {
            token: 'mock-token-' + Date.now(),
            user: { id: 1, name: username }
          },
          status: 200,
          statusText: 'OK',
          headers: {},
          config
        }
      }
      return {
        data: { message: '用户名或密码错误' },
        status: 401,
        statusText: 'Unauthorized',
        headers: {},
        config
      }
    }

    // 注销接口
    if (url.startsWith('/auth/logout') && method === 'post') {
      return {
        data: { success: true },
        status: 200,
        statusText: 'OK',
        headers: {},
        config
      }
    }

    // 用户列表，支持分页：/users?page=1&pageSize=10
    if (url.startsWith('/users') && method === 'get') {
      // 优先读取 params（axios 会将查询参数置于 config.params）
      const page = parseInt(String((config.params && config.params.page) || '1'), 10)
      const pageSize = parseInt(String((config.params && config.params.pageSize) || String(CONFIG.PAGE_SIZE)), 10)
      const all = (window.__mockDB?.users || []).slice()
      const total = all.length
      const start = (page - 1) * pageSize
      const items = all.slice(start, start + pageSize)
      return {
        data: { items, total, page, pageSize },
        status: 200,
        statusText: 'OK',
        headers: {},
        config
      }
    }

    // 表单提交示例
    if (url.startsWith('/form/submit') && method === 'post') {
      const payload = config.data || {}
      // 简单校验：必填字段 name
      if (!payload.name) {
        return {
          data: { message: '名称为必填项' },
          status: 422,
          statusText: 'Unprocessable Entity',
          headers: {},
          config
        }
      }
      return {
        data: { success: true, echo: payload },
        status: 200,
        statusText: 'OK',
        headers: {},
        config
      }
    }

    // 文件上传示例
    if (url.startsWith('/files/upload') && method === 'post') {
      return {
        data: { success: true, fileName: 'uploaded-' + Date.now() },
        status: 200,
        statusText: 'OK',
        headers: {},
        config
      }
    }

    // 文件下载示例
    if (url.startsWith('/files/download') && method === 'get') {
      const blob = new Blob(["示例文件内容"], { type: 'text/plain' })
      return {
        data: blob,
        status: 200,
        statusText: 'OK',
        headers: { 'content-type': 'text/plain' },
        config
      }
    }

    // 默认：回退到原生适配器（便于与真实后端联调）
    return defaultAdapter(config)
  }
}

// 通用方法封装：GET/POST/PUT/DELETE
export const get = (url, params = {}, config = {}) => http.get(url, { params, ...config })
export const post = (url, data = {}, config = {}) => http.post(url, data, config)
export const put = (url, data = {}, config = {}) => http.put(url, data, config)
export const del = (url, params = {}, config = {}) => http.delete(url, { params, ...config })

export default http